package fileApi

import (
	"common/dao/model"
	"common/utils"
	"context"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"

	"file/internal/svc"
	"file/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	req    *http.Request
}

func NewUploadFileLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *UploadFileLogic {
	return &UploadFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		req:    r,
	}
}

func (l *UploadFileLogic) UploadFile() (resp *types.UploadResponse, err error) {
	// todo: add your logic here and delete this line
	file, m, err := l.req.FormFile("file")
	if err != nil {
		return nil, err
	}
	defer func(file multipart.File) {
		err := file.Close()
		if err != nil {
			return
		}
	}(file)
	fmt.Println("123")

	uuid := utils.GetUuid()
	Filename := m.Filename
	size := m.Size
	tsar := utils.GetExtension(Filename)
	sysFile := model.SysFile{
		UUID:   uuid,
		Size:   size,
		Name:   Filename,
		Suffix: "." + tsar,
	}
	fmt.Println(sysFile)
	err = l.svcCtx.DB.Create(&sysFile).Error
	if err != nil {
		return nil, err
	}
	// 设置要保存文件的本地路径
	targetDir, err := os.Getwd()
	fmt.Println(targetDir)
	if err != nil {
		return nil, err
	}
	fileName := uuid + "." + tsar // 可以根据需求动态生成文件名或使用上传的文件名

	// 创建目标文件
	filePath := filepath.Join(targetDir, fileName)
	f, err := os.Create(filePath)
	if err != nil {
		return nil, err
	}
	defer func(f *os.File) {
		err := f.Close()
		if err != nil {
			return
		}
	}(f)

	// 将上传的文件内容复制到目标文件
	_, err = io.Copy(f, file)
	if err != nil {
		return nil, err
	}

	return &types.UploadResponse{
		Uuid: uuid,
	}, nil
}
